Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
JavaScript only code returning "Cannot read properties of undefined" when object property should be defined

I have been trying to figure this out for two hours. The object has the all of the details there, it should be able to find those details once called. But it isn't. Thank you for any help.

if (localStorage.getItem("contactDetails")){
    
    println("Name: " + contact.firstName);
}

else {
    var firstNameVar = prompt("What is your desired first name to log?");
    var lastNameVar = prompt("What is your desired last name to log?");
    var phoneNumVar = prompt("What is your desired phone number to log?");
    
    var contact = {
        firstName: firstNameVar,
        lastName: lastNameVar,
        phoneNum: phoneNumVar
    }
    
    localStorage.setItem("contactDetails", JSON.stringify(contact));
}

The error

I have tried changing between localStorage and directly calling it, I have tried using the object["item"] method rather than just object.item, and a few other things.

EDIT: Going to have to come back to this one. I have tried every single suggestion and it still is not working. My brain is extremely fried from 3 hours of one problem. This is the entire code, there is no more code than this. I'll get back at another time for this. Thank you for your patience!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Try this :

let contact = localStorage.getItem("contactDetails")
if (!!contact){
    
    println("Name: " + contact.firstName);
}

else {
    let firstNameVar = prompt("What is your desired first name to log?");
    let lastNameVar = prompt("What is your desired last name to log?");
    let phoneNumVar = prompt("What is your desired phone number to log?");
    
    contact = {
        firstName: firstNameVar,
        lastName: lastNameVar,
        phoneNum: phoneNumVar
    }
    
    localStorage.setItem("contactDetails", JSON.stringify(contact));
}

PS : Avoid using var , instead use let or const .

Reason why I insist not to use var instead use let or const is as follows :

This code will print Global Variable even though globalVar is defined inside if statement because of scoping property of var .

if(true){
  var globalVar = "Global Variable"
}

console.log(globalVar);

This code will give you an error , as you have not defined scopedLet outside if and still trying to access that variable.

if(true){
  let scopedLet = "Scoped Let variable"
}

console.log(scopedLet);

Same is the case with const.

if(true){
  const scopedConst = "Scoped const variable"
}

console.log(scopedConst)

about 4 years ago · Juan Pablo Isaza Relatório

0

You've got two problems going on here.

One problem is that when you call localStorage.setItem("contactDetails", JSON.stringify(contact));, you are storing a string, so when you call localStorage.getItem("contactDetails") you get a string back. To fix this you need to wrap it in a JSON.parse(), so it looks something like this: JSON.parse(localStorage.getItem("contactDetails")).

The second problem is that you are calling contact.firstName before you define the variable contact. To fix this you need to change your if statement to look like this: if (localStorage.getItem("contactDetails")){ let contact = JSON.parse(localStorage.getItem("contactDetails")) println("Name: " + contact.firstName); }

Hope this makes sense.

about 4 years ago · Juan Pablo Isaza Relatório

0

There are two issues in your code that I have noticed.


Issue #1

You are asking for the value of contact.firstName before it is defined.

To fix this, you need to change the inside of the if statement to the code below.

let t = JSON.parse(localStorage.getItem("contactDetails"))
console.log("Name: " + contact.firstName);

Note: I changed the syntax a little as it didn't look like JavaScript.

Issue #2

When you call JSON.stringify() on your JSON and store it in localStorage, you are storing it in a string. However, when you are getting the key, you are not parsing the JSON. To change it back, you need to use the code below when getting the key.

JSON.parse(localStorage.getItem("contactDetails"));\
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda